<template>
  <view style="background-color: #f2f2f1" v-if="reports.length && pid">
    <view>
      <view style="flex: 1; overflow: auto">
        <th-card title="报检报告">
          <template v-if="pid">
            <th-select
              :options="reports"
              border
              placeholder="请选择报检单号"
              v-model:value="form.checkCode"
              @change="reportChange"
            ></th-select>
          </template>
          <th-form v-if="form.checkCode">
            <th-form-item label="报告单号">
              <view class="text seq-no-text">{{ form.reportCode }}</view>
            </th-form-item>
            <th-form-item label="报检单号">
              <view class="text seq-no-text">
                {{ form.checkCode }}
              </view>
            </th-form-item>
            <th-form-item label="日期">
              <view v-if="[0, 3].includes(form.status)" class="text seq-no-text">
                <th-datetime-picker
                  v-model:value="form.reportDate"
                  format="YYYY-MM-DD"
                  placeholder="请选择日期"
                ></th-datetime-picker>
              </view>
              <text v-else>{{ form.reportDate }}</text>
            </th-form-item>
            <th-form-item label="报检人">
              <view class="text seq-no-text">
                {{ form.inspectName }}
              </view>
            </th-form-item>
            <th-form-item label="任务编码">
              <view class="text seq-no-text">
                {{ form.taskCode }}
              </view>
            </th-form-item>
            <th-form-item label="产品名称">
              <view class="text seq-no-text">
                {{ form.invName }}
              </view>
            </th-form-item>
            <th-form-item label="产品规格">
              <view class="text seq-no-text">
                {{ form.invStd }}
              </view>
            </th-form-item>

            <th-form-item v-if="assayType === 'qcMiddleReport'" label="检验类型">
              <view class="text seq-no-text">
                {{ form.type === 0 ? '中控' : '终检' }}
              </view>
            </th-form-item>
            <block v-if="assayType === 'qcMiddleReport'">
              <th-form-item label="取样时间">
                <view class="text seq-no-text">{{ form.sampleTime }}</view>
              </th-form-item>

              <th-form-item label="取样位置">
                <view class="text seq-no-text">{{ form.position }}</view>
              </th-form-item>

              <th-form-item label="取样工序">
                <view class="text seq-no-text">
                  {{ form.processName }}
                </view>
              </th-form-item>
            </block>
            <th-form-item v-if="assayType === 'qcMiddleReport'" label="样品批号">
              <view class="text seq-no-text">
                {{ form.sampleBatch }}
              </view>
            </th-form-item>
            <th-form-item v-else label="样品编码">
              <view class="text seq-no-text">
                {{ form.sampleCode }}
              </view>
            </th-form-item>

            <th-form-item label="单据状态">
              <view class="text seq-no-text">
                <wd-tag
                  :bg-color="getStatus(form.status)['color']"
                  :color="getStatus(form.status)['color']"
                  plain
                >
                  {{ getStatus(form.status)['label'] }}
                </wd-tag>
              </view>
            </th-form-item>
          </th-form>
        </th-card>
        <th-card title="检测项目">
          <reportTable
            :data="form.qcMiddleReportsList || form.qcExoticReportsList"
            :mode="`${[0, 3].includes(form.status) ? 'form' : 'detail'}`"
            ref="reportRef"
            :reportCode="form.reportCode"
            :cus-flag="form.cusFlag"
            :isPrint="false"
          ></reportTable>
        </th-card>

        <!-- <th-card
          title="审核信息"
          v-if="form.status == '1' || form.status == '2' || form.status == '3'"
        >
          <view class="row-list">
            <view>
              <flowTable ref="flowDetailsTableRef" :processInstanceId="form.instanceId"></flowTable>
            </view>
          </view>
        </th-card> -->
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { reportInfo, pageByTask } from '@/service/pm-assay';
import { formatByDayjs } from '@/utils/util';
import { useDict } from '@/hooks/dict';
import reportTable from './reportTable.vue';
import thSelect from './th-select.vue';
import thDatetimePicker from './th-datetime-picker.vue';

// 接受父组件参数
const props = defineProps({
  pid: {
    type: String,
    defult: '',
  },
  version: {
    type: Number,
    defult: '',
  },
});

const assayType = ref('qcExoticReport');
const assayKey = ref();
const emits = defineEmits(['refresh']);
const flowDetailsTableRef: any = ref({});

// 提交表单数据
const form = ref({
  id: '',
  pid: '', // 报检单id
  reportCode: '',
  checkCode: '',
  reportDate: formatByDayjs(new Date(), 'YYYY-MM-DD'),
  inspectName: '',
  taskCode: '',
  sampleBatch: '',
  sampleCode: '',
  invName: '',
  invStd: '',
  position: '',
  processName: '',
  sampleTime: formatByDayjs(new Date(), 'YYYY-MM-DD HH:mm:ss'),
  type: 0,
  status: undefined,
  taskId: '',
  instanceId: '',
  cusFlag: undefined,
  qcMiddleReportsList: undefined,
  qcExoticReportsList: undefined,
});

const fillInfo = (res) => {
  const {
    reportCode,
    checkCode,
    inspectName,
    taskCode,
    sampleBatch,
    sampleCode,
    position,
    processName,
    sampleTime,
    invName,
    status,
    invStd,
    type,
    cusFlag,
    qcMiddleChecksList,
    qcExoticChecksList,
    qcMiddleReportsList,
    qcExoticReportsList,
  } = res.data;
  form.value.reportCode = reportCode;
  form.value.checkCode = checkCode;
  form.value.inspectName = inspectName;
  form.value.taskCode = taskCode;
  form.value.sampleBatch = sampleBatch;
  form.value.sampleCode = sampleCode;
  form.value.position = position;
  form.value.processName = processName;
  form.value.sampleTime = sampleTime;
  form.value.invName = invName;
  form.value.invStd = invStd;
  form.value.type = type;
  form.value.status = status;
  form.value.cusFlag = cusFlag;

  // 通过id查到的详情
  if (qcMiddleReportsList || qcExoticReportsList) {
    if (qcMiddleReportsList) {
      form.value.qcMiddleReportsList = qcMiddleReportsList;
    } else {
      form.value.qcExoticReportsList = qcExoticReportsList;
    }
  } else {
    const map = {};
    (qcMiddleChecksList || qcExoticChecksList).forEach((item) => {
      if (!map[item.analysisId]) {
        const { id, pid, analysisId, analysisName, indexEntities, equipmentEntities, itemDTOS } =
          item;
        const obj = {
          id,
          pid,
          analysisId,
          analysisName,
          indexEntities,
          equipmentEntities,
          itemDTOS,
        };
        map[item.analysisId] = { ...obj };
      }
    });

    form.value[assayKey.value] = Object.keys(map).map((key) => {
      return map[key];
    });
  }
};

const reportChange = (e: any) => {
  if (!e) return;
  init(e?.id);
};

const init = (id) => {
  uni.showLoading({
    mask: true,
  });

  reportInfo(assayType.value, { id })
    .then((res) => {
      const { id, pid, taskId, instanceId, reportDate } = res.data;
      form.value.id = id;
      form.value.pid = pid;
      form.value.taskId = taskId;
      form.value.instanceId = instanceId;
      form.value.reportDate = reportDate;
      fillInfo(res);
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const reports = ref([]);

onLoad(() => {
  if (!props.pid) return;
  pageByTask({ pid: props.pid, version: props.version, size: 10000 }).then((res) => {
    reports.value = res.data.records.map((item) => {
      return {
        label: item.checkCode,
        value: item.checkCode,
        id: item.id,
        disabled: !item.id,
      };
    });
  });

  reportInfo('qcExoticReport', { pid: props.pid }).then((res) => {
    form.value = { ...res.data };
  });
});

const statusList = [
  {
    text: '未提交',
    value: '0',
    color: '#108ee9',
  },
  {
    text: '审批中',
    value: '1',
    color: '#d46b08',
  },
  {
    text: '已审核',
    value: '2',
    color: '#87d068',
  },
  {
    text: '驳回',
    value: '3',
    color: '#f50',
  },
  {
    text: '撤回',
    value: '9',
    color: '#f50',
  },
];

const { bill_status } = useDict('bill_status');
const getStatus = (status) => {
  if (status == null)
    return {
      text: '未提交',
      value: 0,
      color: '#108ee9',
    };
  const o1 = statusList.find((item) => item.value == status);
  const o = bill_status.value.find((item) => item.value == status);
  return o
    ? {
        ...o,
        color: o1.color,
      }
    : { text: status };
};

const getccReportInfo = (params) => {
  reportInfo('qcMiddleReport', { id: params.id })
    .then((res) => {
      const { id, pid, taskId, instanceId, reportDate } = res.data;
      form.value.id = id;
      form.value.pid = pid;
      form.value.taskId = taskId;
      form.value.instanceId = instanceId;
      form.value.reportDate = reportDate;
      fillInfo(res);
      assayType.value = 'qcMiddleReport';
    })
    .finally(() => {
      uni.hideLoading();
    });
};

defineExpose({
  getccReportInfo,
});
</script>

<style lang="scss" scoped>
.seq-no-text {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  word-break: break-all;
  word-wrap: break-word;
}
</style>
